package com.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pojo.User;
import com.tools.Constants;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import de.hdodenhof.circleimageview.CircleImageView;

public class UserActivity extends AppCompatActivity {

    private CircleImageView 头像;
    private Button 选课;
    private Button 退出登录;

    private TextView 注意,拍照,选择照片,取消;//拍照，从相册中选择图片，取消

    private AlertDialog.Builder builder;//弹框
    private AlertDialog dialog;
    private LayoutInflater inflater;//获取dialog.xml中的三个TextView

    String uid;

    private static String path = "/sdcard/MyHead/";//sd路径
    private Bitmap head;//头像Bitmap

    private Uri imageUri;

    String uploadPath = "http://101.200.40.47:8080/stu/user/uploadAvatar";//上传路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        注意 = (TextView) findViewById(R.id.注意);
        头像 = (CircleImageView) findViewById(R.id.头像);
        选课 = (Button) findViewById(R.id.选课);
        退出登录 = (Button) findViewById(R.id.退出登录);

        uid = Constants.USER_ROOT.getUid();


        //如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
        String downloadPath = "http://101.200.40.47:8080/stu/user/downloadAvatar?pic="+uid+"_head";//加载头像路径
        new downloadImg().execute(downloadPath);


        选课.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(UserActivity.this, ChooseCourseActivity.class);
                startActivity(intent);
                UserActivity.this.finish();
            }
        });


        退出登录.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(UserActivity.this, LoginActivity.class);
                Constants.USER_ROOT.destory();
                startActivity(intent);
                UserActivity.this.finish();
            }
        });

        头像.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder = new AlertDialog.Builder(UserActivity.this);//创建对话框
                inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.dialog_select_photo, null);//获取自定义布局
                builder.setView(layout);//设置对话框的布局
                dialog = builder.create();//生成最终的对话框
                dialog.show();//显示对话框

                拍照 = layout.findViewById(R.id.photograph);
                选择照片 = layout.findViewById(R.id.photo);
                取消 = layout.findViewById(R.id.cancel);

                拍照.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        File outputImage=new File(getExternalCacheDir(), uid +"head.jpg");
                        try {
                            if (outputImage.exists()){
                                outputImage.delete();
                            }
                            outputImage.createNewFile();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                        if (Build.VERSION.SDK_INT>=24){
                            imageUri= FileProvider.getUriForFile(UserActivity.this,"com.change_head.fileprovider",outputImage);
                        }else {
                            imageUri=Uri.fromFile(outputImage);
                        }
                        //相机
                        Intent intent= new Intent("android.media.action.IMAGE_CAPTURE");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                        startActivityForResult(intent, 2);
                        dialog.dismiss();
                    }
                });

                选择照片.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent1 = new Intent(Intent.ACTION_PICK, null);//返回被选中项的URI
                        intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");//得到所有图片的URI
                        startActivityForResult(intent1, 1);
                        dialog.dismiss();
                    }
                });

                取消.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //从相册里面取相片的返回结果
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());//裁剪图片
                }

                break;
            //相机拍照后的返回结果
            case 2:
                if (resultCode == RESULT_OK) {
                    cropPhoto(imageUri);//裁剪图片
                }

                break;
            //调用系统裁剪图片后
            case 3:

                try {
                    head = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    setPicToView(head);//保存在SD卡中
                    头像.setImageBitmap(head);//用ImageView显示出来
                    注意.setVisibility(View.INVISIBLE);
                    File img = new File(path + uid +"_head.jpg");
                    getAsync(img);//async方式
                } catch (FileNotFoundException e) {
                    Toast.makeText(UserActivity.this,"未找到裁剪图片",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    //通过android-async-http上传头像
    public void getAsync(File img) {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        try {
            params.put("file", img);//接口为file时
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        client.post(uploadPath, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Toast.makeText(UserActivity.this, "头像上传成功！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Toast.makeText(UserActivity.this, "头像上传失败!", Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //找到指定URI对应的资源图片

        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        // aspectX aspectY 是裁剪框宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);// 输出图片大小
        intent.putExtra("outputY", 150);



        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        //intent.putExtra("return-data", true);

        imageUri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        //进入系统裁剪图片的界面
        startActivityForResult(intent, 3);

    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd卡是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建以此File对象为名（path）的文件夹
        String fileName = path + uid +"_head.jpg";//图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件（compress：压缩）

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    //加载头像
    private class downloadImg extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET  
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if(o==null){
                注意.setVisibility(View.VISIBLE);
            }else {
                String info = o.toString().trim();
                byte[] bytes = Base64.decode(info, Base64.DEFAULT);
                head =  BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                头像.setImageBitmap(head);
                setPicToView(head);//保存在SD卡中
                注意.setVisibility(View.INVISIBLE);
            }

        }
    }

    long mExitTime;       //实现“再按一次退出”的记录时间变量
    @Override //再按一次退出程序
    public void onBackPressed() {
        if (System.currentTimeMillis() - mExitTime < 2000) {
            super.onBackPressed();
        } else {
            mExitTime = System.currentTimeMillis();
            Toast.makeText(UserActivity.this,"再按一次退出应用",Toast.LENGTH_SHORT).show();
        }
    }
}
